import axios from 'axios'
import { getToken, setToken } from '@/libs/util'
import router from '../router'
let isExpired = false // 是否登录过期
class HttpRequest {
    constructor (baseUrl = '') {
        // 创建 axios 实例
        this.instance = axios.create()
        // 设置默认参数
        this.instance.defaults.baseURL = baseUrl
        // 设置拦截器
        this.interceptors(this.instance)
    }
    // 重新设置token 防止 token 过期直接跳转登录页面(TAPD:1024372)
    setToken (token) {
        const time = new Date().getTime()
        // 节流:1000ms内避免重复设置cookie
        if (!this._time || time - this._time > 1000) {
            setToken(token)
            this._time = time
        }
    }
    interceptors (instance) {
        // 请求拦截
        instance.interceptors.request.use(config => {
            // 设置token
            const token = getToken()
            config.headers = Object.assign({
                Authorization: token
            }, config.headers)
            // 刷新token(过期时间后移2小时，防止 token 过期直接跳转登录页面)(TAPD:1024372)
            token && this.setToken(token)
            return config
        }, error => {
            return Promise.reject(error)
        })
        // 响应拦截
        instance.interceptors.response.use(res => {
            const { data, status } = res
            const result = { data, status }
            if (res.config.responseType === 'arraybuffer') {
                result.headers = res.headers
            }
            if (res.data.code !== '0000') {
                if (res.data.code === '1112') {
                    if (!isExpired) {
                        isExpired = true // 更改状态防止多次请求触发登录信息过期提示
                        setToken('')
                        router.push({ path: '/login' })
                        // window.location.reload()
                    }
                } else {
                    return result
                }
            } else {
                return result
            }
        }, error => {
            return Promise.reject(error)
        })
    }
    request (options) {
        return this.instance(options)
    }
}
export default HttpRequest
